package cn.shop.gateway.view;

import cn.hutool.core.collection.CollectionUtil;
import cn.shop.gateway.MainApp;
import cn.shop.gateway.db.DbUtil;
import cn.shop.gateway.http.ApiUtil;
import cn.shop.gateway.model.MerchantGameTemplate;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.StringConverter;

import java.util.List;
import java.util.Optional;

/**
 * @author : 李一涵
 * @date : Created in 2021-12-10 11:08
 * @description :
 */
public class SelectTemplateController {

    @FXML
    private ChoiceBox<MerchantGameTemplate> choiceBox;
    @FXML
    private Label alert;

    private long id;
    private Stage dialogStage;
    private MainApp app;

    public void setId(long id) {
        this.id = id;
    }

    public void setDialogStage(Stage dialogStage) {
        this.dialogStage = dialogStage;
    }

    public void setApp(MainApp app) {
        this.app = app;
    }

    @FXML
    private void initialize() throws Exception {
        List<MerchantGameTemplate> list = ApiUtil.getTemplates(id);
        if (CollectionUtil.isEmpty(list)) {
            alert.setText("模板信息不存在，请创建模板");
            return;
        }
        choiceBox.converterProperty().set(new StringConverter<MerchantGameTemplate>() {
            @Override
            public String toString(MerchantGameTemplate object) {
                return object.getName();
            }

            @Override
            public MerchantGameTemplate fromString(String string) {
                return null;
            }
        });
        choiceBox.setItems(FXCollections.observableArrayList(list));
        choiceBox.setOnMouseClicked(e -> alert.setText(""));
    }

    @FXML
    public void selectPartition() throws Exception {
        MerchantGameTemplate template = choiceBox.getValue();
        if (template == null) {
            alert.setText("请选择模板");
            return;
        }
        DbUtil.insertGameTemplate(template);
        Optional<Long> templateId = DbUtil.getGameTemplate();
        if (templateId.isPresent()) {
            dialogStage.close();
            app.initRootLayout();
        }
    }

    @FXML
    public void refreshList() throws Exception {
        initialize();
        alert.setText("");
    }

}
